/*
 * File Name：Utils.java
 * Copyright：Copyright 2008-2015 CiWong.Inc. All Rights Reserved.
 * Description： Utils.java
 * Modify By：pla-gysu
 * Modify Date：2015年1月9日
 * Modify Type：Add
 */
package com.ciwong.mobilelib.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Build;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.webkit.URLUtil;

import com.ciwong.libs.utils.StringUtils;

/**
 * 工具类
 * 
 * @author pla-gysu
 * @version ciwong v.1.0 2015年1月9日
 * @since ciwong v.1.0
 */
public class BaseUtils
{

    public static final int MAX_IMAGE_LEN = 8;

    /**
     * 四舍五入
     * 
     * @param time
     *            原始数字
     * @param scale
     *            保留到小数几位
     * @return 四舍五入后的数字
     */
    public static int scaleMath(double time, int scale)
    {
        return new BigDecimal(time).setScale(scale, BigDecimal.ROUND_HALF_UP)
                .intValue();
    }

    /**
     * 判断字符串是否为ip:port|key格式
     * 
     * @param str
     *            字符串
     * @return 是否为tcp格式字符串
     */
    public static boolean isTCPFileFormat(String str)
    {
        if (str == null)
        {
            return false;
        }
        StringBuffer sb = new StringBuffer();
        sb.append("^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])");
        sb.append("\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\\");
        sb.append(".(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\\.");
        sb.append("(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])");
        sb.append(":\\d{1,5}?\\|{1}.*$");
        Pattern pattern = Pattern.compile(sb.toString());
        Matcher matcher = pattern.matcher(str);
        return matcher.find();
    }

    private static InputMethodManager inputMethodManager;

    /**
     * 
     * 显示软键盘
     * 
     * @param context
     *            上下文
     */
    public static void showKeyBoard(Context context)
    {
        inputMethodManager = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.toggleSoftInput(0,
                InputMethodManager.HIDE_IMPLICIT_ONLY);
    }

    /**判断是否为平板
     * @param context
     * @return
     */
    public static boolean isPad(Context context) {
        return (context.getResources().getConfiguration().screenLayout
                & Configuration.SCREENLAYOUT_SIZE_MASK)
                >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    }
    /**
     * 
     * 隐藏键盘
     * 
     * @param context
     *            上下文
     */
    public static void hidKeyBoard(Context context)
    {
        if (context == null)
        {
            return;
        }
        try
        {
            inputMethodManager = (InputMethodManager) context
                    .getSystemService("input_method");
            if (((Activity) context).getCurrentFocus() != null)
            {
                if (((Activity) context).getCurrentFocus().getWindowToken() != null)
                {
                    final int flags = 2;
                    inputMethodManager.hideSoftInputFromWindow(
                            ((Activity) context).getCurrentFocus()
                                    .getWindowToken(), flags);
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    /**
     * 
     * 设置窗口显示在底部
     * 
     * @param act
     */
    public static void setWindowAtBottom(Activity act)
    {
        Window window = act.getWindow();
        if (window != null)
        {
            LayoutParams params = window.getAttributes();
            params.gravity = Gravity.BOTTOM;
            params.width = LayoutParams.MATCH_PARENT;
            window.setAttributes(params);
        }
    }

    /**
     * 获取displaymetrics
     * 
     * @param mContext
     *            上下文
     * @return displaymetrics
     */
    public static DisplayMetrics getDisPlayMetrics(Context mContext)
    {
        Display display = ((WindowManager) mContext
                .getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        DisplayMetrics dm = new DisplayMetrics();
        display.getMetrics(dm);
        return dm;
    }

    /**
     * 移除{@link OnGlobalLayoutListener}事件
     * 
     * @param view
     *            要移除的View
     * @param listener
     *            {@link OnGlobalLayoutListener}
     */
    public static void removeGlobalOnLayoutListener(View view,
            OnGlobalLayoutListener listener)
    {
        if (Integer.parseInt(Build.VERSION.SDK) <= 15)
        {
            view.getViewTreeObserver().removeGlobalOnLayoutListener(listener);
        }
        else
        {
            try
            {
                Method downPolymorphic = view
                        .getViewTreeObserver()
                        .getClass()
                        .getMethod("removeOnGlobalLayoutListener",
                                new Class[]{OnGlobalLayoutListener.class});
                if (downPolymorphic != null)
                    downPolymorphic.invoke(view.getViewTreeObserver(),
                            new Object[]{listener});
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }

    static String[] units = {"", "十", "百", "千", "万", "十万", "百万", "千万", "亿",
            "十亿", "百亿", "千亿", "万亿"};

    static char[] numArray = {'零', '一', '二', '三', '四', '五', '六', '七', '八', '九'};

    /**
     * 阿拉伯数字转换为汉字数字
     * 
     * @param num
     * @return
     */
    public static String formatInteger(int num)
    {
        char[] val = String.valueOf(num).toCharArray();
        int len = val.length;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < len; i++)
        {
            String m = val[i] + "";
            int n = Integer.valueOf(m);
            boolean isZero = n == 0;
            String unit = units[(len - 1) - i];
            if (isZero)
            {
                if ('0' == val[i - 1])
                {
                    // not need process if the last digital bits is 0
                    continue;
                }
                else
                {
                    // no unit for 0
                    sb.append(numArray[n]);
                }
            }
            else
            {
                sb.append(numArray[n]);
                sb.append(unit);
            }
        }
        return sb.toString();
    }

//    /**
//     *
//     * 删除本地语音文件
//     *
//     * @param voicePath
//     * @return
//     */
//    public static boolean deleteVoiceFile(String voicePath)
//    {
//        if (!TextUtils.isEmpty(voicePath))
//        {
//            if (voicePath.indexOf("http") == 0)// 如果是网络地址
//            {
//                voicePath = BaseSystem.getAudioRecordPath() + File.separator
//                        + StringUtils.md5(voicePath);// 得到本地地址
//            }
//            File voiceFile = new File(voicePath);
//            if (voiceFile.exists())
//            {
//                return voiceFile.delete();
//            }
//        }
//        return false;
//    }

    /**
     *
     * 是否是网络地址
     *
     * @param s
     *            地址
     * @return 返回是网络地址为true.
     */
    public static boolean isNetUrl(String s)
    {
        if (URLUtil.isHttpsUrl(s) || URLUtil.isHttpUrl(s)
                || s.contains(".com.cn") || s.contains(".com")
                || s.contains(".net") || s.contains(".edu"))
        {

            return true;
        }
        if (s.contains(".gov") || s.contains(".tel") || s.contains(".org")
                || s.contains(".info") || s.contains(".name")
                || s.contains(".cn"))
        {
            return true;
        }
        return false;
    }
}
